﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TeamNitro.App_Code;
using System.Net.Mail;
using System.Net;
using System.Web.Security;

namespace TeamNitro
{
    public partial class ForgotPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            String AdminEmail = "teamnitro2011@gmail.com";
            String AdminNo = tbxAdminNo.Text;
            String Password = "teamnitro2011";
            String Email = DBManager_Rex.RetrieveEmail(AdminNo);
            String Random = GenerateRandom().ToString();
            bool r = DBManager_Rex.RetrieveUsername(AdminNo);
            if (r == true)
            {

                bool result = DBManager_Rex.ResetPassword(AdminNo, FormsAuthentication.HashPasswordForStoringInConfigFile(Random, "sha1"));
                
                MailMessage mail = new MailMessage();
                mail.To.Add(Email);
                mail.From = new MailAddress(AdminEmail, "Request Reset Password!", System.Text.Encoding.UTF8);
                mail.Subject = "Reset Password!";
                mail.SubjectEncoding = System.Text.Encoding.UTF8;
                mail.Body = "Hi" + " " + AdminNo + ",<br>" + "Reset Code : " + Random;
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.IsBodyHtml = true;
                mail.Priority = MailPriority.High;

                SmtpClient client = new SmtpClient();

                client.Credentials = new NetworkCredential(AdminEmail, Password);

                client.Port = 587;
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true;

                try
                {
                    client.Send(mail);
                }
                catch (Exception ex)
                {
                    Exception ex2 = ex;
                    String errorMessage = String.Empty;
                    while (ex2 != null)
                    {
                        errorMessage += ex2.ToString();
                        ex2 = ex2.InnerException;
                    }
                    HttpContext.Current.Response.Write(errorMessage);
                }
            }




        }
        public static int GenerateRandom()
        {
            Random randNum = new Random();

            int a = randNum.Next(12345678, 87654321);

            return a;            
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        } 

}}